<template>
  <div class="detail-page">
    <el-card v-if="post" class="post-card">
      <div class="author">
        <el-avatar :src="author?.avatarUrl" :size="40"></el-avatar>
        <div class="author-meta">
          <div class="nickname" @click="$router.push('/u/' + (author?.id || post.userId))">
            {{ author?.nickname || author?.username || '用户' + post.userId }}
          </div>
          <div class="time">{{ post.createdAt }}</div>
        </div>
        <div class="ops">
          <el-button
            :type="liked ? 'danger' : 'default'"
            :icon="liked ? 'el-icon-heart' : 'el-icon-heart'"
            :class="{ 'liked-button': liked }"
            @click="toggleLike"
            :loading="likeLoading"
          >
            {{ liked ? '已点赞' : '点赞' }} {{ likeCount }}
          </el-button>
        </div>
      </div>

      <h2 class="title">{{ post.title }}</h2>
      <el-divider></el-divider>

      <!-- 文章内容区域移到上方 -->
      <div class="content" v-html="contentHtml"></div>

      <div class="images">
        <img v-for="img in images" :key="img.id" :src="img.url" />
      </div>
    </el-card>

    <el-card class="comment-card">
      <div class="comment-title">评论</div>
      <el-input
        type="textarea"
        :rows="3"
        v-model="comment"
        placeholder="友善发言，理性交流～"
        @input="onCommentInput"
      />
      <div class="comment-actions">
        <el-button
          type="primary"
          @click="submitComment"
          :disabled="!comment.trim()"
          :loading="commentLoading"
        >
          发布评论
        </el-button>
      </div>

      <div class="comment-list">
        <div class="c-item" v-for="c in comments" :key="c.id">
          <el-avatar :size="32" :src="commentUsers[c.userId]?.avatarUrl"></el-avatar>
          <div class="c-body">
            <div class="c-head">
              <span class="c-name">{{ commentUsers[c.userId]?.nickname || commentUsers[c.userId]?.username || ('用户' + c.userId) }}</span>
              <span class="c-time">{{ c.createdAt }}</span>
            </div>
            <div class="c-text">{{ c.content }}</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      id: null,
      post: null,
      images: [],
      author: null,
      liked: false,
      likeCount: 0,
      likeLoading: false,
      comment: '',
      commentLoading: false,
      comments: [],
      commentUsers: {}
    }
  },
  computed: {
    contentHtml () {
      return (this.post?.content || '').replace(/\n/g, '<br/>')
    }
  },
  async created () {
    this.id = this.$route.params.id
    await this.load()
  },
  methods: {
    async load () {
      const { data } = await axios.get('/api/post/' + this.id)
      if (data.code === 1) {
        this.post = data.data.post
        this.images = data.data.images || []

        // 从数据库实时获取点赞数
        await this.loadLikeCount()

        // 作者信息：若后端详情未携带，则额外请求 /api/user/{id}（请后端提供）
        try {
          const u = await axios.get('/api/user/' + this.post.userId)
          if (u.data.code === 1) this.author = u.data.data
        } catch (e) {}

        await this.loadComments()
        await this.checkLiked()
      }
    },
    async loadLikeCount () {
      try {
        const { data } = await axios.get(`/api/post/${this.id}/like-count`)
        if (data.code === 1) {
          this.likeCount = data.data.likeCount
        }
      } catch (error) {
        console.error('获取点赞数失败:', error)
        this.likeCount = this.post.likeCount || 0
      }
    },
    async loadComments () {
      const c = await axios.get('/api/interact/comments/' + this.id)
      if (c.data.code === 1) {
        this.comments = c.data.data
        // 拉取评论用户头像与昵称（建议后端在评论里直接返回用户简要信息，可省这一步）
        const ids = [...new Set(this.comments.map(i => i.userId))].filter(Boolean)
        await Promise.all(ids.map(async uid => {
          if (this.commentUsers[uid]) return
          try {
            const r = await axios.get('/api/user/' + uid)
            if (r.data.code === 1) this.$set(this.commentUsers, uid, r.data.data)
          } catch (e) {}
        }))
      }
    },
    async checkLiked () {
      try {
        // 从后端接口检查是否已点赞
        const { data } = await axios.get(`/api/interact/is-liked/${this.id}`)
        if (data.code === 1) {
          this.liked = data.data.isLiked
          // 同步更新本地缓存
          const key = 'liked:' + this.id
          if (this.liked) {
            localStorage.setItem(key, '1')
          } else {
            localStorage.removeItem(key)
          }
        }
      } catch (error) {
        // 如果接口失败，使用本地缓存兜底
        console.error('检查点赞状态失败:', error)
        const key = 'liked:' + this.id
        this.liked = localStorage.getItem(key) === '1'
      }
    },
    async toggleLike () {
      if (this.likeLoading) return
      this.likeLoading = true
      try {
        const key = 'liked:' + this.id
        if (!this.liked) {
          const { data } = await axios.post('/api/interact/like/' + this.id)
          if (data.code === 1) {
            this.liked = true
            localStorage.setItem(key, '1')
            // 重新获取最新的点赞数
            await this.loadLikeCount()
            this.$message.success('点赞成功')
          }
        } else {
          const { data } = await axios.post('/api/interact/unlike/' + this.id)
          if (data.code === 1) {
            this.liked = false
            localStorage.removeItem(key)
            // 重新获取最新的点赞数
            await this.loadLikeCount()
            this.$message.success('取消点赞')
          }
        }
      } catch (error) {
        this.$message.error('操作失败，请重试')
      } finally {
        this.likeLoading = false
      }
    },
    onCommentInput () {
      // 实时检查评论内容，用于按钮状态控制
    },
    async submitComment () {
      if (!this.comment.trim()) return this.$message.warning('请输入评论内容')
      this.commentLoading = true
      try {
        const { data } = await axios.post('/api/interact/comment/' + this.id, { content: this.comment.trim() })
        if (data.code === 1) {
          this.comment = ''
          this.$message.success('评论发布成功')
          await this.loadComments()
        } else {
          this.$message.error(data.msg || '评论发布失败')
        }
      } catch (error) {
        this.$message.error('评论发布失败，请重试')
      } finally {
        this.commentLoading = false
      }
    }
  }
}
</script>

<style scoped>
.detail-page{ max-width: 960px; margin: 20px auto; }
.post-card{ margin-bottom: 16px; }
.author{ display:flex; align-items:center; }
.author-meta{ margin-left: 12px; flex:1; }
.nickname{ font-weight: 700; cursor:pointer }
.time{ color:#999; font-size:12px }
.ops{ display:flex; justify-content:flex-end }
.title{ font-size:22px; font-weight:800; margin:12px 0 4px }
.content{ line-height:1.8; font-size:15px; color:#333; margin-bottom:16px }
.images{ display:flex; gap:10px; overflow:auto; margin-bottom:12px }
.images img{ width:280px; height:200px; object-fit:cover; border-radius:6px; box-shadow: 0 6px 18px rgba(0,0,0,.06) }
.comment-card{ }
.comment-title{ font-weight:700; margin-bottom:8px }
.comment-actions{ text-align:right; margin:8px 0 16px }
.comment-list{ }
.c-item{ display:flex; gap:10px; padding:10px 0; border-bottom:1px solid #f0f0f0 }
.c-head{ font-size:12px; color:#888; display:flex; gap:10px }
.c-name{ color:#333; font-weight:600 }
.c-text{ margin-top:4px; white-space:pre-wrap }

/* 点赞按钮样式优化 */
.liked-button {
  background-color: #ff4757 !important;
  border-color: #ff4757 !important;
  color: white !important;
}

.liked-button:hover {
  background-color: #ff3742 !important;
  border-color: #ff3742 !important;
}

/* 评论按钮禁用状态 */
.el-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
